from flask import jsonify
from plantmanagement.models import Record
from plantmanagement.models import Users
from plantmanagement.models import userplant

from plantmanagement.fun import Tools
from datetime import datetime


class UserRecordController:
    def pushRecord(**self):
        userid = self['userid']
        plantid = self['plantid']
        type = self['type']
        d = Record.query.filter(Record.datetimes <= datetime.now()).filter_by(userid=userid, plantid=plantid,
                                                                              type=type).count()
        if d > 0:
            if int(type) == 1:
                return {
                    'code': 201,
                    'msg': '今日以浇过水'
                }
            elif int(type) == 2:
                return {
                    'code': 201,
                    'msg': '今日以施肥'
                }
        else:
            u = Record(userid=userid, plantid=plantid, type=type)
            data = Tools.db_commit(u)
            s = Record.query.filter_by(id=u.id).first()
            if data == 0:
                return {
                    'code': 200,
                    'msg': s.to_json()
                }
            else:
                return {
                    'code': 201,
                    'msg': '失败'
                }

    def GetUserRecordList(**self):
        userid = self['userid']
        plantid = self['plantid']
        d = Record.query.filter_by(userid=userid, plantid=plantid).all()
        # s = userplant.query.filter_by(userid=userid).all()
        t = []
        for a in d:
            t.append(a.to_json())
        return t

    def getPlantInfo(**self):
        userid = self['userid']
        plantid = self['plantid']
        d = userplant.query.filter_by(userid=userid, id=plantid).first()
        print(d)
        return {
            'code': 200,
            'data': d.to_json()
        }

    def login(**self):
        openid = self['openid']
        u = Users.query.filter_by(openid=openid).first()
        z_token = Users.create_token(u.id)
        return {
            'code': 200,
            'data': u.to_json(),
            'token': z_token
        }
